package cn.xtits.xtf.web.springmvc;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

public class DateConverter implements Converter<String, Date> {

    public static final Logger logger = LoggerFactory.getLogger(DateConverter.class);

    public static final String DATE_FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_SECOND = "yyyy-MM-dd";

    @Override
    public Date convert(String source) {
        logger.info("convert source : {}", source);

        DateTimeFormatter formatOne = DateTimeFormat.forPattern(DATE_FORMAT_ONE);
        DateTime dateTime = null;
        Date result = null;
        try {
            dateTime = DateTime.parse(source,formatOne);
            result = dateTime.toDate();
        } catch (Exception e) {
            logger.error("parse error , e ,{}",e);
        }

        if(result == null){
            DateTimeFormatter formatSecond = DateTimeFormat.forPattern(DATE_FORMAT_SECOND);
            dateTime = DateTime.parse(source,formatSecond);
            result = dateTime.toDate();
        }
        if(result == null){
            logger.error("日期转换错误！");
        }
        return result;
    }
}
